var Tool = require("../common/tool.js");
var Login = React.createClass({
    // 组件即将注入时，读取cookie，并显示用户名,功能类似autocomplete
    getInitialState:function(){
        return {
            name:'',
            pwd:''
        }
    },
    componentDidMount: function(){
        if(Tool.getCookie("jchSavaname")){
            // 如果不为空
            var cookiename = Tool.getCookie("jchSavaname");
            // this.refs.name.value = cookiename;
            this.setState({'name':cookiename});
        }
    },
    changeHandle:function(name){
        var that = this;
        return function(event){
            that.setState({[name]:event.target.value});
        }
    },
    login: function(){
        var usrInfo = {};
        usrInfo.name = this.state.name;
        usrInfo.pwd = this.state.pwd;
        if(!this.state.name){
            alert("请输入用户名");
            return;
        }
        if(!this.state.pwd){
            alert("请输入密码");
            return;
        }
        var self = this;
        Tool.post('/login', usrInfo).then(function(data){
            if(data.token){
                // 一、设置token方式：登录成功设置token
                Tool.setToken(data.token);

                // 二、设置cookie方式
                Tool.setCookie('jchTest', self.refs.name.value, 0.5);
                Tool.setCookie("jchSavaname", self.refs.name.value, 7);
                // 成功之后跳转
                location.href="#/place"; //不能这样跳转，这样navBar显示不出来。
                
                
            }
        })
    },
    render: function(){
        return (
            <div className="loginBg">
                <input type="text" className="login" placeholder="用户名" ref="name" value={this.state.name} onChange={this.changeHandle('name')}/>
                <input type="password" className="login" placeholder="密码" ref="pwd" value={this.state.pwd} onChange={this.changeHandle('pwd')}/>
                <button className="loginBtn" onClick={this.login}>登录</button>
            </div>
        );
    }
});

module.exports = Login;